<?php

namespace App\Http\Controllers\Api;

use App\Common\ResponseCode;
use App\Http\Controllers\ApiController;
use App\Models\AdminMenuModel;
use App\Models\AdminUserModel;
use Illuminate\Http\Request;
use Validator;

class LoginController extends ApiController {

    public function login(Request $request)
    {
        $rule = [
            'userName' => 'required',
            'passWord' => 'required',
        ];
        $messages = [
            'userName.required' => '用户名不能为空',
            'passWord.required' => '用户密码不能为空',
        ];

        $error = Validator::make($request->all(), $rule, $messages)->errors()->first();
        if (!empty($error)) {
            return $this->_response(null, ResponseCode::SYSTEM_ERROR, $error);
        }
        $userName = $request->post("userName");
        $passWord = $request->post("passWord");
        $userInfo = AdminUserModel::findRecordOneCondition(["userName" => $userName, "passWord" => $passWord]);
        if (!empty($userInfo)) {
            //城市数据
            $query = AdminUserModel::queryUserCityList();
            $select = ["pc.Name as provinceName", "cc.Name as cityName", "ac.Name as areaName", "auc.provinceId", "auc.cityId", "auc.areaId", "auc.permissionsAreaId"];
            $where = ["auc.userId" => $userInfo["id"]];
            $userCityList = AdminUserModel::getDataJoinList($query, $where, $select)->toArray();
            $userInfo["cityMap"] = $userCityList;
            //权限区域id大于0 的话存入
            $permissionsAreaIds = [];
            foreach ($userCityList as $val) {
                if ($val->permissionsAreaId > 0) {
                    $permissionsAreaIds[] = $val->permissionsAreaId;
                }
            }
            //部门数据
            $deptQuery = AdminUserModel::queryUserDeptList();
            $deptSelect = ["aud.deptId", "ad.deptName"];
            $deptWhere = ["aud.userId" => $userInfo["id"]];
            $userDeptList = AdminUserModel::getDataJoinList($deptQuery, $deptWhere, $deptSelect)->toArray();
            $userInfo["deptMap"] = $userDeptList;
            $deptIds = array_column($userDeptList, "deptId");

            //角色数据
            $roleQuery = AdminUserModel::queryUserRoleList();
            $roleSelect = ["aur.roleId", "ar.roleName", "aur.areaId"];
            $roleWhere = ["aur.userId" => $userInfo["id"]];
            if (!empty($permissionsAreaIds)) {
                $roleWhere["aur.reaId"] = ["wherein" => $permissionsAreaIds];
            }
            $userRoleList = AdminUserModel::getDataJoinList($roleQuery, $roleWhere, $roleSelect)->toArray();
            $userInfo["roleMap"] = $userRoleList;
            $roleIds = array_column($userRoleList, "roleId");

            //权限菜单
            $userInfo["permissionsMenuMap"] = AdminMenuModel::getPermissionParentChildrenList($roleIds, $deptIds);

        }
        return $this->apiResponse($userInfo);
    }
}

